package com.zwb.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zwb.boot.common.R;
import com.zwb.boot.common.utils.RedisUtils;
import com.zwb.boot.common.utils.SMSUtils;
import com.zwb.boot.common.utils.ValidateCodeUtils;
import com.zwb.boot.entity.User;
import com.zwb.boot.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author 头发又黑又长
 * @Date 2022/7/24 15:03
 * @email zwb15083976291@163.com
 */
@Slf4j
@Api("移动端用户")
@RestController
@RequestMapping("/user")
public class UserController {

    @Value("${spring.profiles.active}")
    private String env;

    @Autowired
    private UserService userService;


    @Autowired
    private SMSUtils smsUtils;

    @Autowired
    private RedisUtils redisUtils;

    @Value("${sendMessage.redisPrefix}")
    private String sendMessagePrefix;

    @Value("#{new Long(${sendMessage.expirationTimeSecond})}")
    private Long expirationTime;


    /**
     * 发送短信
     *
     * @param user
     * @param request
     * @return
     * @throws Exception
     */
    @ApiOperation("发送短信接口")
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,
                             HttpServletRequest request) throws Exception {
        String phone = user.getPhone();
        if (ObjectUtils.isEmpty(phone)) {
            return R.error("手机号码为空");
        }
        // 是否是生产环境
        boolean isProd = env.contains("prod");
        String code = ValidateCodeUtils.generateValidateCode(6);
        if (isProd) {
            smsUtils.sendMessage("白天的博客", "SMS_184825163", code.toString(), phone);
        }
        // 设置到 redis中
        redisUtils.setWithExpir(sendMessagePrefix + phone, code, expirationTime);

        R<String> result = R.success("发送成功");
        if (!isProd) {
            result.add("sendMsg", code);
        }
        return result;
    }


    @ApiOperation("用户登录接口")
    @PostMapping("/login")
    public R<Object> login(@RequestBody Map map, HttpServletRequest request) {
        Object phone = map.get("phone");
        Object code = map.get("code");
        if (!(ObjectUtils.isEmpty(phone) || ObjectUtils.isEmpty(code))) {
            // 从redis中获取
            Object sessionCode = redisUtils.getAndDelete(sendMessagePrefix + phone.toString());

            if (!ObjectUtils.isEmpty(sessionCode)) {
                if (sessionCode.toString().equals(code.toString())) {
                    LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(User::getPhone, phone);
                    User user = userService.getOne(queryWrapper);
                    // 如果为空，注册user
                    if (ObjectUtils.isEmpty(user)) {
                        user = new User();
                        user.setPhone(phone.toString());
                        user.setStatus(1);
                        userService.save(user);
                    }
                    request.getSession().setAttribute("user", user.getId());

                    return R.success(user);

                }
            }
        }
        return R.error("登录失败");
    }

}
